package com.purong.purong.activity;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.PermissionConstant;
import com.purong.purong.R;
import com.purong.purong.bean.ArticleBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.widget.LoadingView;
import com.purong.purong.widget.RadiusImageView;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yao.sdk.glide.GlideUtil;
import com.yao.sdk.net.ResponseInfo;
import com.yaoming.umengshare.SharePlatform;
import com.yaoming.umengshare.UmShare;
import com.yaoming.umengshare.listener.ShareResultListener;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by wenjiezeng on 2017/10/10.
 */
public class ArticleDetActivity extends BasePermActivity {
    private ArticleBean articleBean;
    private LoadingView mLoadingView;
    private WebView mWebView;
    private TextView title,date,browse;
    private ImageView favoriteImg;
    private RadiusImageView img;
    private String id;
    private boolean needBack;
    private ProgressBar progressBar;
    @Override
    public void finish() {
        if (needBack&&articleBean!=null){
            Intent intent=new Intent();
            intent.putExtra("ARTICLE",articleBean);
            setResult(RESULT_OK,intent);
        }
        super.finish();
    }
    public void initView(){
        mWebView=(WebView)findViewById(R.id.web_view);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setBlockNetworkImage(false);
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.INVISIBLE);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if(newProgress==100){
                    progressBar.setVisibility(View.INVISIBLE);//加载完网页进度条消失
                }
                else{
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }

            }
        });
        mLoadingView=(LoadingView)findViewById(R.id.loading_view);
        mLoadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getData();
            }

            @Override
            public void onRefresh() {

            }
        });
        img=(RadiusImageView)findViewById(R.id.img);
        title=(TextView)findViewById(R.id.title);
        date=(TextView)findViewById(R.id.date);
        browse=(TextView)findViewById(R.id.browse);
//        content=(TextView)findViewById(R.id.content);
        favoriteImg=(ImageView)findViewById(R.id.favorite_img);
        progressBar=(ProgressBar)findViewById(R.id.progress_bar);
    }

    @Override
    public void initBundle() {
        id=getIntent().getStringExtra("ARTICLE_ID");
        needBack=getIntent().getBooleanExtra("NEED_BACK",false);
    }

    @Override
    public void initData() {
        getData();
    }

    @Override
    public int getRootViewId() {
        return R.layout.activity_article_detial;
    }
    private void getData(){
        mLoadingView.loading();
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("article_id",id);
        if (!request(Contant.ARTICLE_DETAILS, params, true, false)){
            mLoadingView.fail();
        }
    }
    private void setShare(String platform) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (platform.equals("WEIXIN")){
            params.put("share_type", "1");
        }else if (platform.equals("WEIXIN_CIRCLE")){
            params.put("share_type", "2");
        }else if (platform.equals("QQ")){
            params.put("share_type", "3");
        }
        params.put("article_id", id);
        request(Contant.ARTICLE_SHARE_LOG, params, true, false);
    }
    private void setFavourite(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("article_id",articleBean.getArticle_id());
        request(Contant.ARTICLE_FAVORITE, params, true, true);
    }
    private void cancelFavourite(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("article_id",articleBean.getArticle_id());
        request(Contant.ARTICLE_FAVORITE_CANCEL, params, true, true);
    }
    private void setData(){
        if (articleBean.getIs_favorite().equals("1")){
            favoriteImg.setImageResource(R.drawable.nav_icon_collect_nor);
        }else {
            favoriteImg.setImageResource(R.drawable.nav_icon_collect_sel);
        }
        title.setText(articleBean.getTitle());
        date.setText(articleBean.getRelease_time());
        browse.setText(CommonUtil.numConvert(Integer.valueOf(articleBean.getBrowse()),1)+"阅读");
//        content.setText(articleBean.getContent());
//        mWebView.getSettings().setDefaultTextEncodingName("utf-8");

        mWebView.loadDataWithBaseURL(null,articleBean.getContent(),"text/html", "UTF-8",null);

        if (articleBean.getMaster_url()!=null&&!articleBean.getMaster_url().equals("")){
            int width= CommonUtil.getScreenWidth(this)-CommonUtil.dip2px(this,24);
            LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(width,(int)(width*0.569));
            lp.setMargins(0,CommonUtil.dip2px(this,22),0,CommonUtil.dip2px(this,8));
            img.setLayoutParams(lp);
            img.setVisibility(View.VISIBLE);
            GlideUtil.getInstance().load(this,articleBean.getMaster_url(),img,true);
        }

    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.ARTICLE_DETAILS)){
            if (responseInfo.isRequestOk){
                try {
                    articleBean= JSON.parseObject(responseInfo.content,ArticleBean.class);
                    if (articleBean!=null){
                        setData();
                        mLoadingView.finish();
                    }else {
                        mLoadingView.fail();
                    }
                }catch (Exception e){
                    mLoadingView.fail();
                }
            }else {
                mLoadingView.fail();
            }
        }else if (responseInfo.url.equals(Contant.ARTICLE_FAVORITE)){
            if (responseInfo.isRequestOk){
                showToast("已收藏");
                favoriteImg.setImageResource(R.drawable.nav_icon_collect_sel);
                articleBean.setIs_favorite("2");
            }
        }else if (responseInfo.url.equals(Contant.ARTICLE_FAVORITE_CANCEL)){
            if (responseInfo.isRequestOk){
                showToast("已取消收藏");
                favoriteImg.setImageResource(R.drawable.nav_icon_collect_nor);
                articleBean.setIs_favorite("1");
            }
        }

    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.left_back:
                this.finish();
                break;
            case R.id.favorite_img:
                if (articleBean!=null){
                    if (articleBean.getIs_favorite().equals("1")){
                        setFavourite();
                    }else {
                        cancelFavourite();
                    }
                }
                break;
            case R.id.share:
                if (Build.VERSION.SDK_INT >= 23) {
                    checkPermission();
                } else {
                    share();
                }
                break;
        }
    }
    private void share(){
        UmShare share = new UmShare(this, new ShareResultListener() {
            @Override
            public void onStart(String platform) {
                setShare(platform);
            }

            @Override
            public void onSuccess(String platform) {
            }

            @Override
            public void onCancel(String platform) {
            }

            @Override
            public void onError(String platform, Throwable t) {
            }
        });
        if (articleBean.getMaster_url()!=null&&!articleBean.getMaster_url().equals("")){
            share.setImage(articleBean.getMaster_url());
        }else {
            share.setImage(R.mipmap.app_icon);
        }
        share.setText(articleBean.getTitle());
        share.setTitle("普融—中国中小企业普惠金融O2O模式领导者");
        if (articleBean.getShare_url()!=null&&articleBean.getShare_url().startsWith("http")){
            share.setTargetUrl(articleBean.getShare_url());
        }else {
            share.setTargetUrl("http://www.purong.com/");
        }
        share.setPlatform(new SharePlatform(SHARE_MEDIA.WEIXIN),new SharePlatform(SHARE_MEDIA.WEIXIN_CIRCLE),new SharePlatform(SHARE_MEDIA.QQ));
        share.share();
    }

    @Override
    protected String[] getPermissions() {
        return PermissionConstant.PERMS_STORAGE;
    }

    @Override
    protected void doPermissinosSuc() {
        share();
    }
}
